import os
import re
import subprocess
import getpath
import sys
def runCmd(cmd):
    from subprocess import Popen, PIPE, STDOUT
    p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
def mylistdir(p,f):
    a=os.listdir(p)
    fs=myfind(a,f)
    return(fs)
def myfind(l,p):
    lr=[];
    #logging.info p
    p1=p.replace(".",r"\.")
    p2=p1.replace("*",".*")
    p2=p2+"$"
    for a in l:
        #logging.info a
        if  re.search(p2,a,re.IGNORECASE)==None :
           pass
           #logging.info "pass"
        else:
           lr.append(a)
       #logging.info "append"
    return lr 
def mylistdir_r(p,fileStr):
    walk_tree = os.walk(p)
    fs=[]
    for root, subFolders, files in walk_tree:
        for file in files:
            if filepattern(file,fileStr):
                fs.append((root,file))
    return(fs)
def filepattern(filename,p):
    p1=p.replace(".",r"\.")
    p2=p1.replace("*",".*")
    p2=p2+"$"
    if  re.search(p2,filename,re.IGNORECASE)==None :
       return False
    else:
       return True
def getfiles():
    return mylistdir(".","*.ui")
def uiCone(f):    
    (root,filename)=f
    f=os.path.splitext(filename)
    src=os.path.join(root,f[0]+".ui")
    des=os.path.join(root,"ui_"+f[0]+".py")
    if sys.platform == "linux":
        cmd='pyuic5  %s>%s' %(src,des)
    else:    
        exe=r'd:\Python38\scripts\PyQt5-uic.exe'# % getpath.getdrive()
        if os.path.exists(exe):
            cmd=r"""%s %s>%s""" % (exe,src,des)
        else:
            exe=r'%s\Python38\scripts\pyuic5.exe' % getpath.getdrive()
            cmd=r"""%s %s>%s""" % (exe,src,des)
    print(cmd)
    os.system(cmd)
    return cmd
def getfiles_rc(folder):
    return mylistdir(folder,"*.png")
def rCone(f):        
    (root,filename)=f
    f=os.path.splitext(filename)
    src=os.path.join(root,f[0]+".qrc")
    des=os.path.join(root,f[0]+"_rc.py")
    if sys.platform == "linux":
        cmd=r'pyrcc5  %s>%s' %(src,des)
    else:
        exe=r'd:\Python38\scripts\PyQt5-rcc.exe' # % getpath.getdrive()
        if os.path.exists(exe):
            cmd=r"""%s %s>%s""" % (exe,src,des)
        else:
            exe=r'%s\Python38\scripts\pyrcc5.exe' % getpath.getdrive()
            cmd=r"""%s %s >%s""" % (exe,src,des)
    print(cmd)
    os.system(cmd)
    return cmd
def qrc():
    folder="Images"
    fs=getfiles_rc(folder)
    r=[]
    for f in fs:
        one="""<file>%s/%s</file>""" % (folder,f)
        r.append(one)
    instr="\n".join(r)
    out="""<RCC>
    <qresource prefix="/Tao">
        %s
    </qresource>
</RCC>""" % instr
    print(out)
    f=open(folder+".qrc","w")
    f.write(out)
    f.close()
if __name__=="__main__":
    qrc()
